//
//  PVDDetailChecklistCertificatedCell.swift
//  GreenDeal
//
//  Created by Moennig Q on 11/2/2023.
//

import UIKit
import SnapKit
class PVDDetailChecklistCertificatedCell: UITableViewCell {
    let subTitleLabel = ContentLabel(R.font.interRegular(size: 13), hexStr: "#292D32B2")
    lazy var backView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    lazy var typeImageView: UIImageView = {
        return UIImageView()
    }()
    lazy var titleLabel: BaseLabel = {
        let label = ContentLabel(R.font.interSemiBold(size: 16),hexStr: "#292D32FF")
        label.numberOfLines = 2
        return label
    }()
    
    lazy var resultLabel: BaseLabel = {
        let label = ContentLabel(R.font.interMedium(size: 14),hexStr: "#63666AFF")
        label.numberOfLines = 2
        label.adjustsFontSizeToFitWidth = true
        return label
    }()
 
    lazy var moreImageView: UIImageView = {
        return UIImageView(image: UIImage(named: "pvdlist_icon_more"))
    }()
    
    lazy var isRequiredImageView: UIImageView = {
        return UIImageView(image: UIImage(named: "checkListCellStar"))
    }()
    
    lazy var uploadFlagImageView: UIImageView = {
        let image = UIImageView()
        return image
    }()
    var moreImageViewWidthConstraint: Constraint?
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setUpviews()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
    }
    func setUpviews(){
        self.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.contentView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.selectionStyle = .none
        //
        self.contentView.addSubview(backView)
        backView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.height.equalTo(BaseChecklistTableView.checklistCellHeight)
            make.bottom.equalToSuperview()
        }
        //type image view
        typeImageView.contentMode = .center
        backView.addSubview(typeImageView)
        typeImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.width.height.equalTo(30)
            make.centerY.equalToSuperview()
        }
        //uploadFlagImageView,是否上传成功的标记，红色感叹号是本地数据没有上传，绿色勾表示上传成功
        backView.addSubview(uploadFlagImageView)
        uploadFlagImageView.snp.makeConstraints { (make) in
            make.bottom.equalTo(typeImageView)
            make.right.equalTo(typeImageView).offset(3)
            make.size.equalTo(CGSize(width: 16, height: 11))
        }
        //title label
        titleLabel.adjustsFontSizeToFitWidth = true
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(typeImageView.snp.right).offset(12)
            make.centerY.equalTo(typeImageView)
            make.height.width.greaterThanOrEqualTo(0)

        }
        //isRequiredImageView
        backView.addSubview(isRequiredImageView)
        isRequiredImageView.snp.makeConstraints { make in
            make.top.equalTo(typeImageView).offset(6)
            make.left.equalTo(typeImageView.snp.right).offset(4)
            make.height.width.equalTo(7)
        }
        //more image view
        backView.addSubview(moreImageView)
        moreImageView.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.height.equalTo(24)
            self.moreImageViewWidthConstraint = make.width.equalTo(24).constraint
            make.centerY.equalToSuperview()
        }
        //result label
        //抗压缩,抗拉伸能力最强，不会被压缩或拉伸
        resultLabel.setContentHuggingPriority(.required, for: NSLayoutConstraint.Axis.horizontal)
        resultLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        backView.addSubview(resultLabel)
        resultLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.right).offset(5)
            make.right.equalTo(moreImageView.snp.left)
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(0)
            make.centerY.equalToSuperview()
        }
    
        isRequiredImageView.isHidden = true
    }
    
    func setPanelInstalled(){
        self.typeImageView.image = UIImage(named: "installation_detail_checklist_panelinstalled")
        self.resultLabel.isHidden = false
        self.moreImageView.isHidden = false
        if JobDetailModelHelper.shared.jobDetailModel.spv_installed {
            self.resultLabel.text = JobDetailModelHelper.shared.jobDetailModel.system_detail.installation_date
            self.resultLabel.textColor = UIColor(hexStr: "#379657")
            self.moreImageViewWidthConstraint?.update(offset: 0)
        }else{
            self.resultLabel.text = "Onsite\nrequired"
            self.resultLabel.textColor = UIColor(hexStr: "#FFA62D")
            self.moreImageViewWidthConstraint?.update(offset: 24)
        }
    }
    func setData(_ serverModel: PVDChecklistModel,lastRowFlag: Bool,firstRowFlag: Bool)
    {
        self.titleLabel.text = serverModel.title
        let type = serverModel.type
        if firstRowFlag {//第一行
            if lastRowFlag{//最后一行
                self.backView.drawCorner(byRoundingCorners: .allCorners)
            }else{
                self.backView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
            }
        }else{//不是第一行
            if lastRowFlag{//最后一行
                self.backView.drawCorner(byRoundingCorners: [.bottomLeft,.bottomRight])
            }
        }
        //2.check if checklist is requird or optional
        if serverModel.is_required == "true" {
            self.isRequiredImageView.isHidden = false
        }else {
            self.isRequiredImageView.isHidden = true
        }
        //如果开启了SPV，第一条数据要用户Panel Installed检查
        if type == ChecklistType.PanelInstalled.rawValue{
            self.setPanelInstalled()
        }else{//image 类型的包括，checklist的image，noc，coc，other attachment
            self.moreImageViewWidthConstraint?.update(offset: 24)
            self.moreImageView.isHidden = false
            self.titleLabel.text = serverModel.title
            //1.boolean data have not more info
            //3.设置类型图表
            if type == ChecklistType.Image.rawValue{
                switch serverModel.id{
                case ChecklistFixedId.certificateOfElectricalSafety.rawValue:
                    self.typeImageView.image = R.image.jobdetail_checklist_ces_cell_icon()
                case ChecklistFixedId.otherAttachment.rawValue:
                    self.typeImageView.image = R.image.jobdetail_attachment_other_cell_icon()
                case ChecklistFixedId.cocAttachment.rawValue, ChecklistFixedId.nocAttachment.rawValue:
                    self.typeImageView.image = R.image.jobdetail_attachment_noc_cell_icon()
                default:
                    break
                }
                self.uploadFlagImageView.image = (serverModel.haveLocalDataFlag ? R.image.uploadImageFailed() : nil)
            }
            //设置数量
            let imageCnt: Int = serverModel.images.count
            //如果当前checklist是mid-installation check-up或者testing and commissioning checklist而且上一步没有完成
            self.moreImageView.image = UIImage(named: "more_gray_icon")
            
            if imageCnt > 0 {
                if serverModel.minimum_quantity > 0{//只有设置了最小image cnt的才显示这样的格式
                    self.setMinImagesCount(imageCnt, minImageCount: serverModel.minimum_quantity)
                }else{
                    self.resultLabel.text = "#\(imageCnt)"
                }
            }else{
                if serverModel.minimum_quantity > 0{
                    self.setMinImagesCount(0, minImageCount: serverModel.minimum_quantity)
                }else{
                    self.resultLabel.text = ""
                }
            }
        }
        
        
        
    }
    func setMinImagesCount(_ imageCnt: Int, minImageCount: Int64){
        let subStr = "\(imageCnt)"
        let content = subStr + "/\(minImageCount)"
        let attrString = NSMutableAttributedString(string: content )
        let attr1: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#63666A")]
        let attr2: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#379657")]
        
        attrString.addAttributes(attr1, range: NSRange(location: 0, length: attrString.length))
        attrString.addAttributes(attr2, range: NSRange(location: 0, length: subStr.count))
        self.resultLabel.attributedText = attrString
    }
    
}
